package general

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

// Prometheus查询结果的结构
type PrometheusResponse struct {
	Status string `json:"status"`
	Data   struct {
		ResultType string `json:"resultType"`
		Result     []struct {
			Metric map[string]string `json:"metric"`
			Value  []interface{}     `json:"value"`
		} `json:"result"`
	} `json:"data"`
}

func QueryPrometheus(prometheusURL, query string) (*PrometheusResponse, error) {
	// 构建请求URL
	queryURL := fmt.Sprintf("%s/api/v1/query?query=%s", prometheusURL, url.QueryEscape(query))

	// 创建HTTP GET请求
	resp, err := http.Get(queryURL)
	if err != nil {
		return nil, fmt.Errorf("failed to send request: %w", err)
	}
	defer resp.Body.Close()

	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("error: received status code %d", resp.StatusCode)
	}

	// 解析JSON响应
	var result PrometheusResponse
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return nil, fmt.Errorf("failed to decode response: %w", err)
	}

	return &result, nil
}

// ProcessPrometheusData 处理 Prometheus 查询结果，返回一个 PrometheusData 列表
func ProcessPrometheusData(response *PrometheusResponse) ([]PrometheusData, error) {
	if len(response.Data.Result) == 0 {
		return nil, fmt.Errorf("no results found in Prometheus response")
	}

	var dataList []PrometheusData
	for _, result := range response.Data.Result {
		metric := result.Metric

		// 提取值并处理
		value := result.Value
		if len(value) != 2 {
			return nil, fmt.Errorf("invalid value format: %v", value)
		}

		// 转换时间戳
		timestampFloat, ok := value[0].(float64)
		if !ok {
			return nil, fmt.Errorf("invalid timestamp format: %v", value[0])
		}
		timestamp := time.Unix(int64(timestampFloat), 0)

		// 转换指标值
		metricValueStr, ok := value[1].(string)
		if !ok {
			return nil, fmt.Errorf("invalid metric value format: %v", value[1])
		}
		metricValue, err := parseFloatWithPrecision(metricValueStr, 2)
		if err != nil {
			return nil, fmt.Errorf("failed to parse metric value: %w", err)
		}

		// 构造结果
		dataList = append(dataList, PrometheusData{
			Metric: metric,
			Time:   timestamp,
			Value:  metricValue,
		})
	}

	return dataList, nil
}

// parseFloatWithPrecision 将字符串转换为指定精度的浮点数
func parseFloatWithPrecision(valueStr string, precision int) (float64, error) {
	val, err := strconv.ParseFloat(valueStr, 64)
	if err != nil {
		return 0, err
	}
	format := fmt.Sprintf("%%.%df", precision)
	formatted, err := strconv.ParseFloat(fmt.Sprintf(format, val), 64)
	if err != nil {
		return 0, err
	}
	return formatted, nil
}

// PrometheusData 表示处理后的 Prometheus 数据
type PrometheusData struct {
	Metric map[string]string // Prometheus 的 metric 数据
	Time   time.Time         // 时间戳
	Value  float64           // 指标值（保留小数点后两位）
}
